/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */


interface TreeNode {
    val: number,
    left?: TreeNode,
    right?: TreeNode
}


/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrderBottom = function (root: TreeNode) {


    if (!root) {

        return []
    }

    let current: TreeNode[] = [root]
    let nextLevel: TreeNode[] = []

    const res: number[][] = []

    while (current.length > 0) {
        res.unshift(current.map(r => r.val))

        for (const n of  current) {
            n.left && nextLevel.push(n.left)
            n.right && nextLevel.push(n.right)
        }

        current = nextLevel

        nextLevel = []

    }

    return res

};